﻿// *************************************************************************************************
// Project: RealSenseLight
// Namespace: RealSenseLight.ViewModels
// File: ViewModelBase.cs  Author: Peter O'Hanlon
// Copyright © Peter O'Hanlon 2014-2015
// Date: 2015/1/4 21:33
// *************************************************************************************************
using Autofac;
using RealSense.Light.AutoFac;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace RealSenseLight.ViewModels
{
  /// <summary>
  /// Base view model, including the ability to resolve AutoFac resolved instances.
  /// </summary>
  public class ViewModelBase : INotifyPropertyChanged
  {
    private static bool? _inDesignMode;

    /// <summary>
    /// Gets whether or not, we're in design time.
    /// </summary>
    public static bool IsInDesignModeStatic
    {
      get
      {
        if (!_inDesignMode.HasValue)
        {
          _inDesignMode = DesignerProperties.GetIsInDesignMode(new DependencyObject());
        }
        return _inDesignMode.Value;
      }
    }

    /// <summary>
    /// Gets whether or not, we're in design time.
    /// </summary>
    public bool IsInDesignMode
    {
      get
      {
        return IsInDesignModeStatic;
      }
    }

    protected void SetAndNotify<T>(ref T field, T newValue, [CallerMemberName]string property="")
    {
      field = newValue;
      OnChanged(property);
    }

    /// <summary>
    /// Resolve against the container.
    /// </summary>
    /// <typeparam name="T">The instance of T</typeparam>
    /// <returns>The resolved instance, if found.</returns>
    protected T Resolve<T>()
    {
      if (IsInDesignMode)
      {
        return default(T);
      }
      return Bootstrapper.Container.Resolve<T>();
    }

    protected void OnChanged([CallerMemberName]string prop = "")
    {
      var handler = PropertyChanged;
      if (handler == null) return;

      handler(this, new PropertyChangedEventArgs(prop));
    }

    public event PropertyChangedEventHandler PropertyChanged;
  }
}
